import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Button, Modal, Tabs, Form, Input, Select, message } from 'antd';
import { defaultProps } from '../schema';
import { iconOption } from './options';
import { IColumns } from '@inbiz/basic/EditableTable';
import { useForm } from '@formily/react';
import { useQueryFields } from '@inbiz/hooks';
import IconSettings from '../../../Tree/designer/components/IconSettings';
import { getMessage } from '@inbiz/react';

const { TabPane } = Tabs;
type IProps = {
  callBackEvents?: { [key in `on${string}`]: Function };
  emit?: (type: any, ...arg: any) => void;
  onChange?: Function;
  value?: any;
} & typeof defaultProps;
const { Option, OptGroup } = Select;

const SettingView = (props: IProps) => {
  const oldValue = props.value;
  const form = useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [activeKey, $activeKey] = useState('1');

  const sourceModelUpdate = form?.query(/sourceModelUpdate$/)?.take()?.['value'];
  const sourcetype = useMemo(() => {
    if (!sourceModelUpdate) {
      return 'model';
    } else {
      return JSON.parse(sourceModelUpdate).sourcetype;
    }
  }, [sourceModelUpdate]);
  const sourceModel = form.fields?.['form.senior.soure.x-component-props.sourceModel']?.value
  const [fieldsForm] = Form.useForm();
  const IconSettingsRef = useRef(null);
  const [fields] = useQueryFields(
    {
      key: isModalVisible
        ? sourceModel
        : undefined,
      appId: form.appInfo.appId,
    },
    [isModalVisible],
  );

  const fieldsOption: any[] = useMemo(() => {
    let newfieldsOption: any[] = [];
    if (fields.length) {
      (fields || []).forEach((item) => {
        const model = item.origin_FieldName?.split('$')[0];
        const origin = item.origin_FieldName?.split('$')[1];
        if (!newfieldsOption.find((item2) => item2.label == model)) {
          newfieldsOption.push({
            label: model,
            value: item.ModelKey,
            key: item.ModelKey,
            options: [
              {
                label: item.label,
                value: `${origin}$${item.value}`,
                key: `${origin}$${item.value}`,
              },
            ],
          });
        } else {
          newfieldsOption = newfieldsOption.map((item1) => {
            if (model == item1.label) {
              return {
                ...item1,
                options: [
                  ...item1.options,
                  {
                    label: item.label,
                    value: `${origin}$${item.value}`,
                    key: `${origin}$${item.value}`,
                  },
                ],
              };
            } else {
              return item1;
            }
          });
        }
      });
    }
    return newfieldsOption;
  }, [fields]);
  useEffect(() => {
    fieldsForm.setFieldsValue(oldValue.fieldRelation);
  }, [oldValue.fieldRelation]);

  const showModal = () => {
    // 此处获取对应eform示例框的对应的数据
    // if (!form.fields['form.senior.soure.x-component-props.sourceModel']?.value) {
    //   message.warn(getMessage('TreeSelect.tips.pleaseConfigureTheQueryDataSourceFirst'));
    //   return;
    // }
    setIsModalVisible(true);
  };

  const handleOk = async () => {
    const newIconData = await IconSettingsRef.current?.getValue().catch((error) => {
      error.msg && message.error(error.msg);
      $activeKey('1');
      throw error;
    });
    await fieldsForm.validateFields().catch((error) => {
      $activeKey('2');
      throw error;
    });

    props.onChange?.({
      IconsSettings: newIconData,
      fieldRelation: fieldsForm.getFieldsValue(true),
    });
    setIsModalVisible(false);
  };

  const handleCancel = async () => {
    fieldsForm.setFieldsValue(oldValue.fieldRelation);
    $activeKey('1');
    setIsModalVisible(false);
  };

  const changeTabs = useCallback((activeKey) => {
    $activeKey(activeKey);
  }, []);

  const filedSelect = useMemo(() => {
    if ((sourcetype === 'model' || sourcetype == '') && sourceModel) {
      return (
        <Select
        showSearch
        filterOption={(input, option) =>
         (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
       }
         style={{ width: '100%' }} optionLabelProp={'label'}>
          {fieldsOption?.map((item) => {
            return (
              <OptGroup label={item.label}>
                {item.options?.map((item1: any) => {
                  return (
                    <Option value={item1.value} key={item1.label} label={item1.label}>
                      {item1.label.indexOf('.') != -1 ? item1.label.split('.')[1] : item1.label}
                    </Option>
                  );
                })}
              </OptGroup>
            );
          })}
        </Select>
      );
    } else {
      return <Input style={{ width: '100%' }} />;
    }
  }, [sourcetype, fieldsOption]);

  return (
    <>
      <Button type="primary" onClick={showModal}>
        {getMessage('TreeSelect.configbtn')}
      </Button>
      <Modal
        title={getMessage('TreeSelect.configbtn')}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={900}
        destroyOnClose={true}
        isMove
        okText={getMessage('global.sure')}
        cancelText={getMessage('TreeSelect.cancel')}
      >
        <Tabs activeKey={activeKey} onChange={changeTabs}>
          <TabPane tab={getMessage('TreeSelect.icon')} key="1" forceRender={true}>
            <IconSettings
              ref={IconSettingsRef}
              value={props.value}
              fieldsOption={fieldsOption}
              isInput={sourcetype !== 'model'}
              type="treeSelect"
            />
          </TabPane>
          <TabPane tab={getMessage('TreeSelect.condition')} key="2" forceRender={true}>
            <Form form={fieldsForm} labelCol={{ span: 6 }} wrapperCol={{ span: 8 }}>
              <Form.Item
                name="id"
                label={getMessage('TreeSelect.nodeid')}
                required
                rules={[
                  {
                    required: true,
                    message: getMessage('TreeSelect.tips.pleaseSelectAndOptionFirst'),
                  },
                ]}
              >
                {filedSelect}
              </Form.Item>
              <Form.Item
                name="label"
                label={getMessage('TreeSelect.nodetext')}
                required
                rules={[
                  {
                    required: true,
                    message: getMessage('TreeSelect.tips.pleaseSelectAndOptionFirst'),
                  },
                ]}
              >
                {filedSelect}
              </Form.Item>
              <Form.Item
                name="parentId"
                label={getMessage('TreeSelect.parentnodeid')}
                required
                rules={[
                  {
                    required: true,
                    message: getMessage('TreeSelect.tips.pleaseSelectAndOptionFirst'),
                  },
                ]}
              >
                {filedSelect}
              </Form.Item>
              <Form.Item name="rootId" label={getMessage('TreeSelect.rootid')}>
                <Input style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item name="selectedId" label={getMessage('TreeSelect.defaultselectid')}>
                <Input style={{ width: '100%' }} />
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Modal>
    </>
  );
};

export default SettingView;
